package user

import (
	"gitee.com/code_batcher/avatar/pkg/auth"
	"gitee.com/code_batcher/avatar/pkg/shell"
	"github.com/gofiber/fiber/v3"
)

func Login(ctx fiber.Ctx) (err error) {
	sshAuth := new(ShellAuth)
	if err = ctx.Bind().Body(sshAuth); err != nil {
		return err
	}

	if sshAuth.Port == 0 {
		sshAuth.Port = 22
	}

	sshClient, err := shell.Login(sshAuth.Host, sshAuth.User, sshAuth.Password, sshAuth.Port)
	if err != nil {
		return fiber.ErrForbidden
	}
	_ = sshClient.Close()

	token, err := auth.Sign(sshAuth.User, nil)
	if err != nil {
		return fiber.ErrInternalServerError
	}

	ctx.Set("Authorization", "Bearer "+token)

	return nil
}
